import json
from urllib.request import urlopen


def getWeather(code):
    # 1.获取API
    url = "https://restapi.amap.com/v3/weather/weatherInfo?city={}&key=xxxxx&output=JSON&extensions=base".format(
        code)
    res = urlopen(url)
    # 返回数据解码
    data = json.loads(res.read())
    print(data)
    # 数据格式输出
    # print(data['lives'][0])
    # print(data['lives'][0]['province'])
    province = data['lives'][0]['province']  # 省份
    city = data['lives'][0]['city']  # 城市
    weather = data['lives'][0]['weather']  # 天气情况
    temperature = data['lives'][0]['temperature']  # 温度
    winddirection = data['lives'][0]['winddirection']  # 风向
    windpower = data['lives'][0]['windpower']  # 风力 级
    humidity = data['lives'][0]['humidity']  # 空气湿度
    reporttime = data['lives'][0]['reporttime']  # 发布时间
    return_msg = "%s%s 天气情况如, 天气：%s-温度：%sC 空气湿度：%s" % (province, city, weather, temperature, humidity)
    print(return_msg)
    print(data['lives'][0]['province'])
    print(f"实时天气：{province}{city}")


# 调用函数
getWeather('110101')
